package model

import (
	"database/sql"
	"github.com/doujunyu/gogo/sql_aid"
	"time"
)

const TableByUserLoginEquipment = "self_user_login_equipment"

const UserLoginEquipmentByIsOnlineNo = 0 //离线
const UserLoginEquipmentByIsOnlineYes = 1 //在线

const UserLoginEquipmentByIsDelYes = 1 //已删除
const UserLoginEquipmentByIsDelNo = 0 //未删除

// UserLoginEquipmentByNewEquipment 用户第一次用新设备登录添加数据
func UserLoginEquipmentByNewEquipment(tx *sql.Tx,userId int64,equipment string,linkServer string,portIp string)error{
	t := time.Now().Format(time.RFC3339)
	insert := make(map[string]interface{})
	insert["user_id"] = userId
	insert["equipment"] = equipment
	insert["is_online"] = UserLoginEquipmentByIsOnlineYes
	insert["is_del"] = UserLoginEquipmentByIsDelNo
	insert["time_u"] = t
	insert["time_c"] = t
	insert["link_server"] = linkServer
	insert["port_ip"] = portIp
	insertSql,args := sql_aid.PgTable(TableByUserLoginEquipment).InsertByMap(insert)
	_,err := tx.Exec(insertSql,args...)
	if err != nil {
		return err
	}
	return nil
}

// UserLoginEquipmentByOldEquipment 用户登录有老设备
func UserLoginEquipmentByOldEquipment(tx *sql.Tx,userId int64,equipment string,linkServer string,portIp string)error{
	t := time.Now().Format(time.RFC3339)
	update := make(map[string]interface{})
	update["is_online"] = UserLoginEquipmentByIsOnlineYes
	update["is_del"] = UserLoginEquipmentByIsDelNo
	update["time_u"] = t
	update["link_server"] = linkServer
	update["port_ip"] = portIp
	updateSql,args := sql_aid.PgTable(TableByUserLoginEquipment).Where("user_id = ?",userId).Where("equipment = ?",equipment).UpdateByMap(update)
	_,err := tx.Exec(updateSql,args...)
	if err != nil {
		return err
	}
	return nil
}

// UserLoginEquipmentByExit 用户退出更改状态
func UserLoginEquipmentByExit(tx *sql.Tx, userId int64,equipment string)error{
	t := time.Now().Format(time.RFC3339)
	update := make(map[string]interface{})
	update["is_online"] = UserLoginEquipmentByIsOnlineNo
	update["time_u"] = t
	updateSql,args := sql_aid.PgTable(TableByUserLoginEquipment).Where("user_id = ?",userId).Where("equipment = ?",equipment).UpdateByMap(update)
	_,err := tx.Exec(updateSql,args...)
	if err != nil {
		return err
	}
	return nil

}

